
<!DOCTYPE HTML>
<html lang="zh-hans" >
    <head>
        <title>useState · React源码解析</title>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="generator" content="GitBook 3.2.0">
        
        
        
    
    <link rel="stylesheet" href="../../gitbook/style.css">

    
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-highlight/website.css">
                
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-search/search.css">
                
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-fontsettings/website.css">
                
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-theme-api/theme-api.css">
                
            
        

    

    
        
        <link rel="stylesheet" href="../../styles/website.css">
        
    
        
    
        
    
        
    
        
    
        
    

         
    
    
    <meta name="HandheldFriendly" content="true"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../../gitbook/images/apple-touch-icon-precomposed-152.png">
    <link rel="shortcut icon" href="../../gitbook/images/favicon.ico" type="image/x-icon">

    
    <link rel="next" href="hooks-use-effect.html" />
    
    
    <link rel="prev" href="hooks-start.html" />
    

<script
  async
  src="https://www.googletagmanager.com/gtag/js?id=UA-49483742-5"
></script>
<script>
  window.dataLayer = window.dataLayer || []
  function gtag() {
    dataLayer.push(arguments)
  }
  gtag('js', new Date())

  gtag('config', 'UA-49483742-5')
</script>

    </head>
    <body>
        
<div class="book">
    <div class="book-summary">
        
            
<div id="book-search-input" role="search">
    <input type="text" placeholder="输入并搜索" />
</div>

            
                <nav role="navigation">
                


<ul class="summary">
    
    

    

    
        
        
    
        <li class="chapter " data-level="1.1" data-path="../../">
            
                <a href="../../">
            
                    
                    首页
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2" >
            
                <span>
            
                    
                    基础
            
                </span>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.2.1" data-path="../api/react.html">
            
                <a href="../api/react.html">
            
                    
                    React API
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.2" data-path="../api/react-element.html">
            
                <a href="../api/react-element.html">
            
                    
                    ReactElement
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.3" data-path="../api/react-children.html">
            
                <a href="../api/react-children.html">
            
                    
                    React Children
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.4" data-path="../api/react-structure.html">
            
                <a href="../api/react-structure.html">
            
                    
                    React 中的数据结构
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.3" >
            
                <span>
            
                    
                    创建更新
            
                </span>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.3.1" data-path="../update/react-dom-render.html">
            
                <a href="../update/react-dom-render.html">
            
                    
                    ReactDOM.render
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3.2" data-path="../update/set-state.html">
            
                <a href="../update/set-state.html">
            
                    
                    setState & forceUpdate
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3.3" data-path="../update/expiration-time.html">
            
                <a href="../update/expiration-time.html">
            
                    
                    expirationTime 计算
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.4" >
            
                <span>
            
                    
                    任务调度
            
                </span>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.4.1" data-path="../flow/scheduler-global.html">
            
                <a href="../flow/scheduler-global.html">
            
                    
                    全局变量
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.2" data-path="../flow/schedule-work.html">
            
                <a href="../flow/schedule-work.html">
            
                    
                    scheduleWork
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.3" data-path="../flow/scheduler-pkg.html">
            
                <a href="../flow/scheduler-pkg.html">
            
                    
                    react-scheduler
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.4" data-path="../flow/perform-work.html">
            
                <a href="../flow/perform-work.html">
            
                    
                    performWork
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.5" data-path="../flow/perform-unit-of-work.html">
            
                <a href="../flow/perform-unit-of-work.html">
            
                    
                    performUnitOfWork
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.6" data-path="../flow/render-root.html">
            
                <a href="../flow/render-root.html">
            
                    
                    renderRoot
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.4.6.1" data-path="../flow/render-root/throw-exception.html">
            
                <a href="../flow/render-root/throw-exception.html">
            
                    
                    throwException
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.4.7" data-path="../flow/begin-work.html">
            
                <a href="../flow/begin-work.html">
            
                    
                    beginWork
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.4.7.1" data-path="../flow/begin-work/mount-indeterminate-component.html">
            
                <a href="../flow/begin-work/mount-indeterminate-component.html">
            
                    
                    mountIndeterminateComponent
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.7.2" data-path="../flow/begin-work/mount-lazy-component.html">
            
                <a href="../flow/begin-work/mount-lazy-component.html">
            
                    
                    mountLazyComponent
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.7.3" data-path="../flow/begin-work/update-functional-component.html">
            
                <a href="../flow/begin-work/update-functional-component.html">
            
                    
                    updateFunctionalComponent
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.7.4" data-path="../flow/begin-work/update-class-component.html">
            
                <a href="../flow/begin-work/update-class-component.html">
            
                    
                    updateClassComponent
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.7.5" data-path="../flow/begin-work/update-host-root.html">
            
                <a href="../flow/begin-work/update-host-root.html">
            
                    
                    updateHostRoot
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.7.6" data-path="../flow/begin-work/update-host-component.html">
            
                <a href="../flow/begin-work/update-host-component.html">
            
                    
                    updateHostComponent
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.7.7" data-path="../flow/begin-work/update-host-text.html">
            
                <a href="../flow/begin-work/update-host-text.html">
            
                    
                    updateHostText
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.7.8" data-path="../feature/Suspense-component.md">
            
                <span>
            
                    
                    updateSuspenseComponent
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.7.9" data-path="../flow/begin-work/update-portal-component.html">
            
                <a href="../flow/begin-work/update-portal-component.html">
            
                    
                    updatePortalComponent
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.7.10" data-path="../flow/begin-work/update-forward-ref.html">
            
                <a href="../flow/begin-work/update-forward-ref.html">
            
                    
                    updateForwardRef
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.7.11" data-path="../flow/begin-work/update-fragment.html">
            
                <a href="../flow/begin-work/update-fragment.html">
            
                    
                    updateFragment
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.7.12" data-path="../flow/begin-work/update-mode.html">
            
                <a href="../flow/begin-work/update-mode.html">
            
                    
                    updateMode
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.7.13" data-path="../flow/begin-work/update-profiler.html">
            
                <a href="../flow/begin-work/update-profiler.html">
            
                    
                    updateProfiler
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.7.14" data-path="../flow/begin-work/update-context-provider.html">
            
                <a href="../flow/begin-work/update-context-provider.html">
            
                    
                    updateContextProvider
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.7.15" data-path="../flow/begin-work/update-context-consumer.html">
            
                <a href="../flow/begin-work/update-context-consumer.html">
            
                    
                    updateContextConsumer
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.4.8" data-path="../flow/reconcile-children.html">
            
                <a href="../flow/reconcile-children.html">
            
                    
                    reconcileChildren
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.4.8.1" data-path="../flow/reconcile-children/single.html">
            
                <a href="../flow/reconcile-children/single.html">
            
                    
                    调和单个节点
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.8.2" data-path="../flow/reconcile-children/array.html">
            
                <a href="../flow/reconcile-children/array.html">
            
                    
                    调和列表
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.5" >
            
                <span>
            
                    
                    commit 阶段
            
                </span>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.5.1" data-path="../commit-phase/commit-root.html">
            
                <a href="../commit-phase/commit-root.html">
            
                    
                    commitRoot
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.2" data-path="../commit-phase/invokeGuardedCallback.html">
            
                <a href="../commit-phase/invokeGuardedCallback.html">
            
                    
                    invokeGuardedCallback
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.3" data-path="../commit-phase/commitBeforeMutationLifecycles.html">
            
                <a href="../commit-phase/commitBeforeMutationLifecycles.html">
            
                    
                    commitBeforeMutationLifecycles
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.4" data-path="../commit-phase/commit-all-host-effects.html">
            
                <a href="../commit-phase/commit-all-host-effects.html">
            
                    
                    commitAllHostEffects
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.5.4.1" data-path="../commit-phase/host-effects/CommitPlacement.html">
            
                <a href="../commit-phase/host-effects/CommitPlacement.html">
            
                    
                    commitPlacement
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.4.2" data-path="../commit-phase/host-effects/CommitWork.html">
            
                <a href="../commit-phase/host-effects/CommitWork.html">
            
                    
                    commitWork
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.4.3" data-path="../commit-phase/host-effects/CommitDeletion.html">
            
                <a href="../commit-phase/host-effects/CommitDeletion.html">
            
                    
                    commitDeletion
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.5.5" data-path="../commit-phase/commit-all-lifecycles.html">
            
                <a href="../commit-phase/commit-all-lifecycles.html">
            
                    
                    commitAllLifecycle
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.6" >
            
                <span>
            
                    
                    功能
            
                </span>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.6.1" data-path="../features/context.html">
            
                <a href="../features/context.html">
            
                    
                    context
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.2" data-path="../features/hydrate.html">
            
                <a href="../features/hydrate.html">
            
                    
                    hydrate
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.3" data-path="../features/ref.html">
            
                <a href="../features/ref.html">
            
                    
                    ref
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.4" data-path="../features/event-injection.html">
            
                <a href="../features/event-injection.html">
            
                    
                    事件系统初始化
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.5" data-path="../features/event-bind.html">
            
                <a href="../features/event-bind.html">
            
                    
                    事件绑定
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.6" data-path="../features/event-dispatch.html">
            
                <a href="../features/event-dispatch.html">
            
                    
                    事件触发
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.7" data-path="../features/event-create-event-object.html">
            
                <a href="../features/event-create-event-object.html">
            
                    
                    事件对象生成
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.8" data-path="../features/Suspense-component.html">
            
                <a href="../features/Suspense-component.html">
            
                    
                    Suspense
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.9" data-path="../features/suspense.html">
            
                <a href="../features/suspense.html">
            
                    
                    挂起任务的含义
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.10" data-path="../features/suspense-lazy.html">
            
                <a href="../features/suspense-lazy.html">
            
                    
                    lazy 组件
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.7" >
            
                <span>
            
                    
                    Hooks
            
                </span>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.7.1" data-path="hooks-start.html">
            
                <a href="hooks-start.html">
            
                    
                    开始
            
                </a>
            

            
        </li>
    
        <li class="chapter active" data-level="1.7.2" data-path="hooks-use-state.html">
            
                <a href="hooks-use-state.html">
            
                    
                    useState
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.7.3" data-path="hooks-use-effect.html">
            
                <a href="hooks-use-effect.html">
            
                    
                    useEffect
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.7.4" data-path="hooks-others.html">
            
                <a href="hooks-others.html">
            
                    
                    其他API
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.7.5" data-path="hooks-common.html">
            
                <a href="hooks-common.html">
            
                    
                    通用API
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    

    

    <li class="divider"></li>

    <li>
        <form
            action="https://buttondown.email/api/emails/embed-subscribe/Jokcy"
            method="post"
            target="popupwindow"
            onsubmit="window.open('https://buttondown.email/Jokcy', 'popupwindow')"
            class="buttondown-form"
            >
            <input type="email" name="email" id="bd-email" placeholder="(your@email.com)">
            <input type="hidden" value="1" name="embed"/>
            <button type="submit">订阅我</button>
        </form>
    </li>
</ul>

                </nav>
            
        
    </div>

    <div class="book-body">
        
            <div class="body-inner">
                 
                    

<div class="book-header" role="navigation">
    

    <!-- Title -->
    <h1>
        <i class="fa fa-circle-o-notch fa-spin"></i>
        <a href="../.." >useState</a>
    </h1>
</div>




                    <div class="page-wrapper" tabindex="-1" role="main">
                        <div class="page-inner">
                            
<div id="book-search-results">
    <div class="search-noresults">
    
                                <section class="normal markdown-section">
                                
                                <h1 id="usestate">useState</h1><p>&#x5F53;&#x6211;&#x4EEC;&#x7684;&#x4EE3;&#x7801;&#x6267;&#x884C;&#x5230;&#x4E86;<code>useState</code>&#x7684;&#x65F6;&#x5019;&#xFF0C;&#x4ED6;&#x5230;&#x5E95;&#x505A;&#x4E86;&#x4EC0;&#x4E48;&#x5462;&#xFF1F;</p><pre><code class="lang-js">function basicStateReducer&lt;S&gt;(state: S, action: BasicStateAction&lt;S&gt;): S {
  return typeof action === &apos;function&apos; ? action(state) : action;
}

export function useState&lt;S&gt;(
  initialState: (() =&gt; S) | S,
): [S, Dispatch&lt;BasicStateAction&lt;S&gt;&gt;] {
  return useReducer(
    basicStateReducer,
    // useReducer has a special case to support lazy useState initializers
    (initialState: any),
  );
}</code></pre>
<p>&#x53EF;&#x89C1;<code>useState</code>&#x4E0D;&#x8FC7;&#x5C31;&#x662F;&#x4E2A;&#x8BED;&#x6CD5;&#x7CD6;&#xFF0C;&#x672C;&#x8D28;&#x5176;&#x5B9E;&#x5C31;&#x662F;<code>useReducer</code>&#xFF0C;&#x90A3;&#x4E48;<code>useReducer</code>&#x5177;&#x4F53;&#x505A;&#x4E86;&#x4EC0;&#x4E48;&#x5462;&#xFF1F;</p><div class="api-method"><div class="api-method-definition"><h3 id="usereducer">useReducer</h3><p>&#x6700;&#x5F00;&#x59CB;&#x7684;&#x4E24;&#x53E5;&#x4EE3;&#x7801;&#x662F;&#x6BCF;&#x4E2A;Hooks&#x90FD;&#x4F1A;&#x505A;&#x7684;&#x7EDF;&#x4E00;&#x4EE3;&#x7801;&#xFF1A;</p><pre><code class="lang-js">currentlyRenderingFiber = resolveCurrentlyRenderingFiber();
workInProgressHook = createWorkInProgressHook();</code></pre>
<ul><li><a href="hooks-common.html"><code>currentlyRenderingFiber</code></a>
</li>
<li><a href="hooks-common.html"><code>createWorkInProgressHook</code></a>
</li></ul>
<p>&#x8FD9;&#x91CC;&#x5206;&#x4E24;&#x79CD;&#x60C5;&#x51B5;&#xFF1A;<em>&#x7B2C;&#x4E00;&#x6B21;&#x6E32;&#x67D3;</em>&#x548C;<em>&#x66F4;&#x65B0;</em>&#xFF0C;&#x5982;&#x679C;<code>workInProgressHook.queue</code>&#x5B58;&#x5728;&#x5219;&#x4E3A;<em>&#x66F4;&#x65B0;</em>&#xFF0C;&#x5426;&#x5219;&#x662F;<em>&#x7B2C;&#x4E00;&#x6B21;&#x6E32;&#x67D3;</em></p><h3 id="&#x7B2C;&#x4E00;&#x6B21;&#x6E32;&#x67D3;">&#x7B2C;&#x4E00;&#x6B21;&#x6E32;&#x67D3;</h3><p>&#x7B2C;&#x4E00;&#x6B21;&#x6E32;&#x67D3;&#x4E3B;&#x8981;&#x5C31;&#x662F;&#x521D;&#x59CB;&#x5316;&#x64CD;&#x4F5C;</p><pre><code class="lang-js"><span class="hljs-comment">// There&apos;s no existing queue, so this is the initial render.</span>
<span class="hljs-keyword">if</span> (reducer === basicStateReducer) {
  <span class="hljs-comment">// Special case for `useState`.</span>
  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> initialState === <span class="hljs-string">&apos;function&apos;</span>) {
    initialState = initialState();
  }
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (initialAction !== <span class="hljs-literal">undefined</span> &amp;&amp; initialAction !== <span class="hljs-literal">null</span>) {
  initialState = reducer(initialState, initialAction);
}
workInProgressHook.memoizedState = workInProgressHook.baseState = initialState;</code></pre>
<p>&#x8FD9;&#x91CC;&#x521D;&#x59CB;&#x5316;<code>initialState</code>&#xFF0C;&#x5E76;&#x4E14;&#x8BB0;&#x5F55;&#x5728;<code>workInProgressHook.memoizedState</code>&#x548C;<code>workInProgressHook.baseState</code>&#x4E0A;</p><p>&#x7136;&#x540E;&#x521B;&#x5EFA;<code>queue</code>&#x5BF9;&#x8C61;</p><pre><code class="lang-js">queue = workInProgressHook.queue = {
  last: <span class="hljs-literal">null</span>,
  dispatch: <span class="hljs-literal">null</span>,
};</code></pre>
<p>&#x8FD9;&#x4E00;&#x770B;&#x5230;<code>queue</code>&#x7684;&#x7ED3;&#x6784;&#x975E;&#x5E38;&#x7B80;&#x5355;&#xFF0C;&#x53EA;&#x6709;&#x4E00;&#x4E2A;<code>last</code>&#x6307;&#x9488;&#x548C;<code>dispatch</code>&#xFF0C;<code>dispatch</code>&#x662F;&#x7528;&#x6765;&#x8BB0;&#x5F55;<strong>&#x66F4;&#x65B0;<code>state</code>&#x7684;&#x65B9;&#x6CD5;&#x7684;</strong>&#xFF0C;&#x63A5;&#x4E0B;&#x53BB;&#x6211;&#x4EEC;&#x5C31;&#x8981;&#x521B;&#x5EFA;<code>dispatch</code>&#x65B9;&#x6CD5;&#x4E86;</p><pre><code class="lang-js"><span class="hljs-keyword">const</span> dispatch: Dispatch&lt;A&gt; = (queue.dispatch = (dispatchAction.bind(
  <span class="hljs-literal">null</span>,
  currentlyRenderingFiber,
  queue,
): any));</code></pre>
<p>&#x53EF;&#x4EE5;&#x770B;&#x5230;&#x8FD9;&#x4E2A;<code>dispatch</code>&#x5C31;&#x662F;<code>dispatchAction</code>&#x7ED1;&#x5B9A;&#x4E86;&#x5BF9;&#x5E94;&#x7684;<code>Fiber</code>&#x548C;<code>queue</code>&#x3002;&#x6700;&#x540E;<code>return</code>&#xFF1A;</p><pre><code class="lang-js"><span class="hljs-keyword">return</span> [workInProgressHook.memoizedState, dispatch];</code></pre>
<p>&#x5BF9;&#x5E94;&#x4E86;&#x6211;&#x4EEC;<code>const [state, updateState] = useState(&apos;default&apos;)</code>&#x7684;&#x7528;&#x6CD5;</p><h3 id="&#x66F4;&#x65B0;">&#x66F4;&#x65B0;</h3><p>&#x5206;&#x4E24;&#x79CD;&#x60C5;&#x51B5;&#xFF0C;<strong>&#x662F;&#x5426;&#x662F;<code>reRender</code></strong>&#xFF0C;&#x6240;&#x8C13;<code>reRender</code>&#x5C31;&#x662F;&#x8BF4;&#x5728;<strong>&#x5F53;&#x524D;&#x66F4;&#x65B0;&#x5468;&#x671F;&#x4E2D;&#x53C8;&#x4EA7;&#x751F;&#x4E86;&#x65B0;&#x7684;&#x66F4;&#x65B0;&#xFF0C;&#x5C31;&#x7EE7;&#x7EED;&#x6267;&#x884C;&#x8FD9;&#x4E9B;&#x66F4;&#x65B0;&#x77E5;&#x9053;&#x5F53;&#x524D;&#x6E32;&#x67D3;&#x5468;&#x671F;&#x4E2D;&#x6CA1;&#x6709;&#x66F4;&#x65B0;&#x4E3A;&#x6B62;</strong></p><p>&#x4ED6;&#x4EEC;&#x57FA;&#x672C;&#x7684;&#x64CD;&#x4F5C;&#x662F;&#x4E00;&#x81F4;&#x7684;&#xFF0C;&#x5C31;&#x662F;&#x6839;&#x636E;<code>reducer</code>&#x548C;<code>update.action</code>&#x6765;&#x521B;&#x5EFA;&#x65B0;&#x7684;<code>state</code>&#xFF0C;&#x5E76;&#x8D4B;&#x503C;&#x7ED9;<code>Hook.memoizedState</code>&#x4EE5;&#x53CA;<code>Hook.baseState</code>&#x3002;</p><p>&#x6CE8;&#x610F;&#x8FD9;&#x91CC;&#xFF0C;&#x5BF9;&#x4E8E;&#x975E;<code>reRender</code>&#x5F97;&#x60C5;&#x51B5;&#xFF0C;&#x6211;&#x4EEC;&#x4F1A;&#x5BF9;&#x6BCF;&#x4E2A;&#x66F4;&#x65B0;&#x5224;&#x65AD;&#x5176;&#x4F18;&#x5148;&#x7EA7;&#xFF0C;&#x5982;&#x679C;&#x4E0D;&#x662F;&#x5F53;&#x524D;&#x6574;&#x4F53;&#x66F4;&#x65B0;&#x4F18;&#x5148;&#x7EA7;&#x5185;&#x5F97;&#x66F4;&#x65B0;&#x4F1A;&#x8DF3;&#x8FC7;&#xFF0C;&#x7B2C;&#x4E00;&#x4E2A;&#x8DF3;&#x8FC7;&#x5F97;<code>Update</code>&#x4F1A;&#x53D8;&#x6210;&#x65B0;&#x7684;<code>baseUpdate</code>&#xFF0C;<strong>&#x4ED6;&#x8BB0;&#x5F55;&#x4E86;&#x5728;&#x4E4B;&#x540E;&#x6240;&#x6709;&#x5F97;<code>Update</code>&#xFF0C;&#x5373;&#x4FBF;&#x662F;&#x4F18;&#x5148;&#x7EA7;&#x6BD4;&#x4ED6;&#x9AD8;&#x5F97;&#xFF0C;&#x56E0;&#x4E3A;&#x5728;&#x4ED6;&#x88AB;&#x6267;&#x884C;&#x5F97;&#x65F6;&#x5019;&#xFF0C;&#x9700;&#x8981;&#x4FDD;&#x8BC1;&#x540E;&#x7EED;&#x7684;&#x66F4;&#x65B0;&#x8981;&#x5728;&#x4ED6;&#x66F4;&#x65B0;&#x4E4B;&#x540E;&#x7684;&#x57FA;&#x7840;&#x4E0A;&#x518D;&#x6B21;&#x6267;&#x884C;&#xFF0C;&#x56E0;&#x4E3A;&#x7ED3;&#x679C;&#x53EF;&#x80FD;&#x4F1A;&#x4E0D;&#x4E00;&#x6837;&#x3002;</strong></p></div><div class="api-method-code"><div class="api-method-sample" data-lang="js" data-name="JavaScript"><pre><code class="lang-js">export function useReducer&lt;S, A&gt;(
  reducer: (S, A) =&gt; S,
  initialState: S,
  initialAction: A | void | null,
): [S, Dispatch&lt;A&gt;] {
  currentlyRenderingFiber = resolveCurrentlyRenderingFiber();
  workInProgressHook = createWorkInProgressHook();
  let queue: UpdateQueue&lt;A&gt; | null = (workInProgressHook.queue: any);
  if (queue !== null) {
    // Already have a queue, so this is an update.
    if (isReRender) {
      // This is a re-render. Apply the new render phase updates to the previous
      // work-in-progress hook.
      const dispatch: Dispatch&lt;A&gt; = (queue.dispatch: any);
      if (renderPhaseUpdates !== null) {
        // Render phase updates are stored in a map of queue -&gt; linked list
        const firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
        if (firstRenderPhaseUpdate !== undefined) {
          renderPhaseUpdates.delete(queue);
          let newState = workInProgressHook.memoizedState;
          let update = firstRenderPhaseUpdate;
          do {
            // Process this render phase update. We don&apos;t have to check the
            // priority because it will always be the same as the current
            // render&apos;s.
            const action = update.action;
            newState = reducer(newState, action);
            update = update.next;
          } while (update !== null);

          workInProgressHook.memoizedState = newState;

          // Don&apos;t persist the state accumlated from the render phase updates to
          // the base state unless the queue is empty.
          // TODO: Not sure if this is the desired semantics, but it&apos;s what we
          // do for gDSFP. I can&apos;t remember why.
          if (workInProgressHook.baseUpdate === queue.last) {
            workInProgressHook.baseState = newState;
          }

          return [newState, dispatch];
        }
      }
      return [workInProgressHook.memoizedState, dispatch];
    }

    // The last update in the entire queue
    const last = queue.last;
    // The last update that is part of the base state.
    const baseUpdate = workInProgressHook.baseUpdate;

    // Find the first unprocessed update.
    let first;
    if (baseUpdate !== null) {
      if (last !== null) {
        // For the first update, the queue is a circular linked list where
        // `queue.last.next = queue.first`. Once the first update commits, and
        // the `baseUpdate` is no longer empty, we can unravel the list.
        last.next = null;
      }
      first = baseUpdate.next;
    } else {
      first = last !== null ? last.next : null;
    }
    if (first !== null) {
      let newState = workInProgressHook.baseState;
      let newBaseState = null;
      let newBaseUpdate = null;
      let prevUpdate = baseUpdate;
      let update = first;
      let didSkip = false;
      do {
        const updateExpirationTime = update.expirationTime;
        if (updateExpirationTime &lt; renderExpirationTime) {
          // Priority is insufficient. Skip this update. If this is the first
          // skipped update, the previous update/state is the new base
          // update/state.
          if (!didSkip) {
            didSkip = true;
            newBaseUpdate = prevUpdate;
            newBaseState = newState;
          }
          // Update the remaining priority in the queue.
          if (updateExpirationTime &gt; remainingExpirationTime) {
            remainingExpirationTime = updateExpirationTime;
          }
        } else {
          // Process this update.
          const action = update.action;
          newState = reducer(newState, action);
        }
        prevUpdate = update;
        update = update.next;
      } while (update !== null &amp;&amp; update !== first);

      if (!didSkip) {
        newBaseUpdate = prevUpdate;
        newBaseState = newState;
      }

      workInProgressHook.memoizedState = newState;
      workInProgressHook.baseUpdate = newBaseUpdate;
      workInProgressHook.baseState = newBaseState;
    }

    const dispatch: Dispatch&lt;A&gt; = (queue.dispatch: any);
    return [workInProgressHook.memoizedState, dispatch];
  }

  // There&apos;s no existing queue, so this is the initial render.
  if (reducer === basicStateReducer) {
    // Special case for `useState`.
    if (typeof initialState === &apos;function&apos;) {
      initialState = initialState();
    }
  } else if (initialAction !== undefined &amp;&amp; initialAction !== null) {
    initialState = reducer(initialState, initialAction);
  }
  workInProgressHook.memoizedState = workInProgressHook.baseState = initialState;
  queue = workInProgressHook.queue = {
    last: null,
    dispatch: null,
  };
  const dispatch: Dispatch&lt;A&gt; = (queue.dispatch = (dispatchAction.bind(
    null,
    currentlyRenderingFiber,
    queue,
  ): any));
  return [workInProgressHook.memoizedState, dispatch];
}</code></pre>
</div></div></div>



<hr><div class="api-method"><div class="api-method-definition"><h3 id="dispatchaction">dispatchAction</h3><p>&#x9996;&#x5148;&#x770B;&#x8FD9;&#x4E2A;&#x5224;&#x65AD;&#xFF1A;</p><pre><code class="lang-js"><span class="hljs-keyword">if</span> (
  fiber === currentlyRenderingFiber ||
  (alternate !== <span class="hljs-literal">null</span> &amp;&amp; alternate === currentlyRenderingFiber)
)</code></pre>
<p>&#x8FD9;&#x5176;&#x5B9E;&#x5C31;&#x662F;&#x5224;&#x65AD;&#x8FD9;&#x4E2A;&#x66F4;&#x65B0;&#x662F;&#x5426;&#x662F;&#x5728;<strong>&#x6E32;&#x67D3;&#x8FC7;&#x7A0B;&#x4E2D;&#x4EA7;&#x751F;&#x7684;</strong>&#xFF0C;<code>currentlyRenderingFiber</code>&#x53EA;&#x6709;&#x5728;<code>FunctionalComponent</code>&#x66F4;&#x65B0;&#x7684;&#x8FC7;&#x7A0B;&#x4E2D;&#x624D;&#x4F1A;&#x88AB;&#x8BBE;&#x7F6E;&#xFF0C;&#x5728;&#x79BB;&#x5F00;&#x66F4;&#x65B0;&#x7684;&#x65F6;&#x5019;&#x8BBE;&#x7F6E;&#x4E3A;<code>null</code>&#xFF0C;&#x6240;&#x4EE5;&#x53EA;&#x8981;&#x5B58;&#x5728;&#x5E76;&#x66F4;&#x4EA7;&#x751F;&#x66F4;&#x65B0;&#x7684;<code>Fiber</code>&#x76F8;&#x7B49;&#xFF0C;&#x8BF4;&#x660E;&#x8FD9;&#x4E2A;&#x66F4;&#x65B0;&#x662F;&#x5728;&#x5F53;&#x524D;&#x6E32;&#x67D3;&#x4E2D;&#x4EA7;&#x751F;&#x7684;&#xFF0C;&#x5219;&#x8FD9;&#x662F;&#x4E00;&#x6B21;<code>reRender</code>&#x3002;</p><p>&#x6240;&#x6709;&#x66F4;&#x65B0;&#x8FC7;&#x7A0B;&#x4E2D;&#x4EA7;&#x751F;&#x7684;&#x66F4;&#x65B0;&#x8BB0;&#x5F55;&#x5728;<code>renderPhaseUpdates</code>&#x8FD9;&#x4E2A;Map&#x4E0A;&#xFF0C;&#x4EE5;&#x6BCF;&#x4E2A;<code>Hook</code>&#x7684;<code>queue</code>&#x4E3A;<code>key</code>&#x3002;</p><p>&#x5BF9;&#x4E8E;&#x4E0D;&#x662F;&#x66F4;&#x65B0;&#x8FC7;&#x7A0B;&#x4E2D;&#x4EA7;&#x751F;&#x7684;&#x66F4;&#x65B0;&#xFF0C;&#x5219;&#x76F4;&#x63A5;&#x5728;<code>queue</code>&#x4E0A;&#x6267;&#x884C;&#x64CD;&#x4F5C;&#x5C31;&#x884C;&#x4E86;&#xFF0C;&#x6CE8;&#x610F;&#x5728;&#x6700;&#x540E;&#x4F1A;&#x53D1;&#x8D77;&#x4E00;&#x6B21;<code>scheduleWork</code>&#x7684;&#x8C03;&#x5EA6;&#x3002;</p></div><div class="api-method-code"><div class="api-method-sample" data-lang="js" data-name="JavaScript"><pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">dispatchAction</span>&lt;<span class="hljs-title">A</span>&gt;(<span class="hljs-params">fiber: Fiber, queue: UpdateQueue&lt;A&gt;, action: A</span>) </span>{
  invariant(
    numberOfReRenders &lt; RE_RENDER_LIMIT,
    <span class="hljs-string">&apos;Too many re-renders. React limits the number of renders to prevent &apos;</span> +
      <span class="hljs-string">&apos;an infinite loop.&apos;</span>,
  );

  <span class="hljs-keyword">const</span> alternate = fiber.alternate;
  <span class="hljs-keyword">if</span> (
    fiber === currentlyRenderingFiber ||
    (alternate !== <span class="hljs-literal">null</span> &amp;&amp; alternate === currentlyRenderingFiber)
  ) {
    <span class="hljs-comment">// This is a render phase update. Stash it in a lazily-created map of</span>
    <span class="hljs-comment">// queue -&gt; linked list of updates. After this render pass, we&apos;ll restart</span>
    <span class="hljs-comment">// and apply the stashed updates on top of the work-in-progress hook.</span>
    didScheduleRenderPhaseUpdate = <span class="hljs-literal">true</span>;
    <span class="hljs-keyword">const</span> update: Update&lt;A&gt; = {
      expirationTime: renderExpirationTime,
      action,
      next: <span class="hljs-literal">null</span>,
    };
    <span class="hljs-keyword">if</span> (renderPhaseUpdates === <span class="hljs-literal">null</span>) {
      renderPhaseUpdates = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();
    }
    <span class="hljs-keyword">const</span> firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
    <span class="hljs-keyword">if</span> (firstRenderPhaseUpdate === <span class="hljs-literal">undefined</span>) {
      renderPhaseUpdates.set(queue, update);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-comment">// Append the update to the end of the list.</span>
      <span class="hljs-keyword">let</span> lastRenderPhaseUpdate = firstRenderPhaseUpdate;
      <span class="hljs-keyword">while</span> (lastRenderPhaseUpdate.next !== <span class="hljs-literal">null</span>) {
        lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
      }
      lastRenderPhaseUpdate.next = update;
    }
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">const</span> currentTime = requestCurrentTime();
    <span class="hljs-keyword">const</span> expirationTime = computeExpirationForFiber(currentTime, fiber);
    <span class="hljs-keyword">const</span> update: Update&lt;A&gt; = {
      expirationTime,
      action,
      next: <span class="hljs-literal">null</span>,
    };
    flushPassiveEffects();
    <span class="hljs-comment">// Append the update to the end of the list.</span>
    <span class="hljs-keyword">const</span> last = queue.last;
    <span class="hljs-keyword">if</span> (last === <span class="hljs-literal">null</span>) {
      <span class="hljs-comment">// This is the first update. Create a circular list.</span>
      update.next = update;
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">const</span> first = last.next;
      <span class="hljs-keyword">if</span> (first !== <span class="hljs-literal">null</span>) {
        <span class="hljs-comment">// Still circular.</span>
        update.next = first;
      }
      last.next = update;
    }
    queue.last = update;
    scheduleWork(fiber, expirationTime);
  }
}</code></pre>
</div></div></div>




                                
                                </section>
                            
    </div>
    <div class="search-results">
        <div class="has-results">
            
            <h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
            <ul class="search-results-list"></ul>
            
        </div>
        <div class="no-results">
            
            <h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
            
        </div>
    </div>
</div>

                        </div>
                    </div>
                
<div id="disqus_thread"></div>
<script>
  /**
   *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
   *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/
  /*
var disqus_config = function () {
this.page.url = PAGE_URL;  // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
  ;(function() {
    // DON'T EDIT BELOW THIS LINE
    var d = document,
      s = d.createElement('script')
    s.src = 'https://react-source-code.disqus.com/embed.js'
    s.setAttribute('data-timestamp', +new Date())
    ;(d.head || d.body).appendChild(s)
  })()
</script>
<noscript
  >Please enable JavaScript to view the
  <a href="https://disqus.com/?ref_noscript"
    >comments powered by Disqus.</a
  ></noscript
>

            </div>

            

        
    </div>

    <script>
        var gitbook = gitbook || [];
        gitbook.push(function() {
            gitbook.page.hasChanged({"page":{"title":"useState","level":"1.7.2","depth":2,"next":{"title":"useEffect","level":"1.7.3","depth":2,"path":"book/hooks/hooks-use-effect.md","ref":"book/hooks/hooks-use-effect.md","articles":[]},"previous":{"title":"开始","level":"1.7.1","depth":2,"path":"book/hooks/hooks-start.md","ref":"book/hooks/hooks-start.md","articles":[]},"dir":"ltr"},"config":{"plugins":["theme-api"],"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"pluginsConfig":{"sharing":{"facebook":false,"twitter":false,"google":false,"weibo":true,"instapaper":false,"vk":false,"all":["weibo","google","twitter","weibo","instapaper"]},"highlight":{},"search":{},"lunr":{"maxIndexSize":1000000,"ignoreSpecialCharacters":false},"fontsettings":{"theme":"white","family":"sans","size":2},"theme-api":{"languages":[],"split":true,"theme":"light"},"theme-default":{"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":false}},"theme":"default","pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"variables":{},"title":"React源码解析","language":"zh-hans","gitbook":"*"},"file":{"path":"book/hooks/hooks-use-state.md","mtime":"2019-02-12T16:31:29.423Z","type":"markdown"},"gitbook":{"version":"3.2.0","time":"2019-07-08T12:28:32.264Z"},"basePath":"../..","book":{"language":""}});
        });
    </script>
</div>

        
    <script src="../../gitbook/gitbook.js"></script>
    <script src="../../gitbook/theme.js"></script>
    
        
        <script src="../../gitbook/gitbook-plugin-search/search-engine.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-search/search.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-lunr/lunr.min.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-lunr/search-lunr.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-sharing/buttons.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-theme-api/theme-api.js"></script>
        
    

    </body>
</html>

